import { prisma } from '@/lib/prisma';
import { notFound, redirect } from 'next/navigation';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/auth.config';
import { DestinationForm } from '../../DestinationForm';
import { unstable_noStore as noStore } from 'next/cache';

async function getDestination(id: string) {
  // 禁用缓存
  noStore();
  
  const session = await getServerSession(authOptions);
  if (!session?.user?.id) {
    redirect('/api/auth/signin');
  }

  const destination = await prisma.destination.findUnique({
    where: { 
      id,
      createdById: session.user.id  // 确保只能编辑自己创建的目的地
    },
    include: {
      activities: {
        orderBy: {
          date: 'asc'
        }
      },
      _count: {
        select: {
          activities: true
        }
      },
      savedBy: true
    }
  });

  if (!destination) {
    notFound();
  }

  // 转换 metadata 为正确的类型
  return {
    ...destination,
    metadata: destination.metadata ? JSON.parse(JSON.stringify(destination.metadata)) : null
  };
}

export default async function EditDestinationPage({
  params
}: {
  params: { id: string }
}) {
  const destination = await getDestination(params.id);

  return (
    <div className="max-w-4xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
      <h1 className="text-3xl font-bold text-blue-900 mb-8">编辑目的地</h1>
      <DestinationForm destination={destination} />
    </div>
  );
} 